import React, { useReducer } from "react";

const FormContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "add_data":
      return [...state, action.payload.newData];
    case "add_all_data":
      return action.payload.value;
    case "edit_data":
      return state.map((item, index) => {
        return index == action.payload.key ? action.payload.value : item;
      });
    case "delete_data":
      return state.filter((item, index) => index !== action.payload.index);
    default:
      return state;
  }
};

let initData = [
  // {
  //   type: "铜锌",
  //   detail: {
  //     specs: {
  //       shape: [1, "圆形"],
  //       length: ["3", 2],
  //       width: ["2", 2],
  //       radius: ["2", 2],
  //     },
  //     basePlate: {
  //       category: [1, "铜"],
  //       thickness: ["2", 2],
  //       type: [0, "QF87"],
  //     },
  //     shroudPlate: {
  //       category: [0, "锌"],
  //       thickness: ["2", 2],
  //       type: [1, "H89"],
  //     },
  //     amount: "11",
  //   },
  // },
  // {
  //   type: "铁铝",
  //   detail: {
  //     specs: {
  //       shape: [0, "长方形"],
  //       length: ["3", 0],
  //       width: ["2", 0],
  //       radius: ["2", 0],
  //     },
  //     basePlate: {
  //       category: [2, "铁"],
  //       thickness: ["2", 2],
  //       type: [4, "tie3"],
  //     },
  //     shroudPlate: {
  //       category: [3, "铝"],
  //       thickness: ["2", 2],
  //       type: [2, "7070"],
  //     },
  //     amount: "11",
  //   },
  // },
];

export const FormProvider = ({ children }) => {
  const [formData, dispatch] = useReducer(dataReducer, initData);
  // console.log("initFormData---", formData);

  const addData = (newData) => {
    dispatch({ type: "add_data", payload: { newData } });
  };

  const editData = (key, value) => {
    dispatch({
      type: "edit_data",
      payload: { key: key, value: value },
    });
  };

  const addAllData = (value) => {
    dispatch({
      type: "add_all_data",
      payload: { value: value },
    });
  };

  const deleteFormItem = (index) => {
    dispatch({
      type: "delete_data",
      payload: { index: index },
    });
  };

  return (
    <FormContext.Provider
      value={{
        formData: formData,
        addData,
        editData,
        addAllData,
        deleteFormItem,
      }}
    >
      {children}
    </FormContext.Provider>
  );
};

export default FormContext;
